var helper = require('../../../utils/helper.js'), integral_catId = 0, integral_index = -1, page = 1, go;

Page({
    data: {
        hasUserInfo: false,
        currentTab: -1,
        navScrollLeft: 0,
        goods_list: [],
        subcat: [],
        scrollTop: {
            scroll_top: 0,
            goTop_show: false
        },
        cat_checked: true,
        cat_checked1:true,
        hot_goods: [],
        hoimg: 'https://tuibao.renrentuibao.com/addons/zjhj_mall/core/web/statics/images/',
        catId: 0,
        promotion: [],
        page_url: '',
        pro_url: '',
        totalCount: '0',
        remind: false,
        surprise: {},
        str_time: '',
        integral_catId: 0,
        is_distributor:'',
        adds:1,
        pays:{},
        signaTop:'',
        bannerHeight: 0,  //banner高度
        scrollToptt: 0, //滚动条高度
    },
    onLoad: function (t) {
        var that = this
        getApp().page.onLoad(this, t), integral_catId = 0, integral_index = -1;
        wx.getSystemInfo({
            success: (res) => {
                this.setData({
                    pixelRatio: res.pixelRatio,
                    windowHeight: res.windowHeight,
                    windowWidth: res.windowWidth
                })
            },
        })
        wx.createSelectorQuery().select('#hegao').boundingClientRect((rect) => {
            this.setData({
              bannerHeight: rect.height +740
            })
          }).exec()
        let menuButton= wx.getMenuButtonBoundingClientRect()
        this.setData({
           signaTop:menuButton.top,
        })   
        getApp().request({
            url: getApp().api.integral.index,
            data: {},
            success: function (t) {
                if (t.code == 0) {
                    if(t.data.user == null){
                        a.setData({
                            // banner_list: t.data.banner_list,
                            coupon_list: t.data.coupon_list,
                            catList: t.data.cat_list,
                            catList1: t.data.cat_list,
                            promotion: t.data.promotion,
                            page_url: t.data.promotion.page_url,
                            pro_url: t.data.promotion.pro_url,
                            surprise: t.data.activity,
                        })
                    }else{
                        a.setData({
                            // banner_list: t.data.banner_list,
                            coupon_list: t.data.coupon_list,
                            integral: t.data.user.integral,
                            catList: t.data.cat_list,
                            catList1: t.data.cat_list,
                            promotion: t.data.promotion,
                            page_url: t.data.promotion.page_url,
                            pro_url: t.data.promotion.pro_url,
                            surprise: t.data.activity,
                            is_distributor:t.data.user.is_distributor
                        })
                    }


                }
                if (0 == t.code && (t.data.today && a.setData({
                    register_day: 1
                }), -1 != integral_index)) {
                    var e = [];
                    e.index = integral_index, e.catId = integral_catId

                }
            },
            complete: function (t) {
                getApp().core.hideLoading();
            }
        });
        page = 1, this.getGoodsList(integral_catId);
        var a = this;
    
        a.hot_goods(integral_catId)

    },
    onUnload: function () {
        clearInterval(go);
    },
    onPageScroll:function(e){
        this.setData({
            scrollToptt: e.scrollTop
          })
    },
    pay_success: function (d) {
        var that = this
        getApp().request({
          url: getApp().api.order.pay_success_integral,
          data: {
            order_id: d
          },
          success: function (t) {
            console.log('pay==',t)
            if ( t.code == 0) {
              that.setData({
                pays:t.data
              })
            }
          }
        })
      },

    //热销好物
    hot_goods: function (e) {
        var a = this;
        getApp().request({
            url: getApp().api.integral.hot_goods,
            data: {
                cat_id: e
            },
            success: function (t) {
                console.log('人气好物', t)
                if (t.code === 0) {
                    a.setData({
                        hot_goods: t.data
                    })
                }
            },
            complete: function (t) {
                getApp().core.hideLoading();
            }
        });
    },
    //更多热销好物
    hotgoods: function (e) {
        var a = this
        console.log('data=', a.data)
        wx.navigateTo({
            url: '../hotgoods/hotgoods?cat_id=' + a.data.catId + '&is_distributor=' + a.data.is_distributor,
        })
    },

    onGoodsImageClick: function (e) {
        var page_url = e.currentTarget.dataset.page_url
        console.log('page_url', page_url)
        wx.navigateTo({
            url: page_url,

        })
    },
    onReady: function (t) {
        getApp().page.onReady(this);
    },
    introduce:function(e){
        wx.navigateTo({
            url: '/pages/goods/goods?id=1168'+ "&xr=1",
        })

    },
    
    onShow: function (t) {
        getApp().page.onShow(this);
        var a = this;
        if (wx.getStorageSync('ACCESS_TOKEN')) {
            var fordata = helper.formatData(new Date());
            console.log('shijian===', fordata)
            // this.ss()
            if (fordata === wx.getStorageSync('fordata')) {
                console.log('今天以提醒')
                this.setData({
                    remind: false
                })
            } else {
                console.log('今天未提醒')
                wx.setStorageSync('fordata', fordata)
                this.setData({
                    remind: true,
                    adds:1
                })
            }
        };
        var adds = wx.getStorageSync('adds')
        console.log('fffffffsggggggg=',adds)
        if(adds == '2'){
          console.log('jinlaifffffgg')
          var address_id = wx.getStorageSync('address_id')
          this.setData({
              remind:true,
              adds:adds
          })
            this.pay_success(address_id)
        };

    },
    exchangeCoupon: function (t) {
        var a = this, n = a.data.coupon_list, e = t.currentTarget.dataset.index, o = n[e], i = a.data.integral;
        if (parseInt(o.integral) > parseInt(i)) a.setData({
            showModel: !0,
            content: "当前爱心不足",
            status: 1
        }); else {
            if (0 < parseFloat(o.price)) var s = "需要" + o.integral + "爱心+￥" + parseFloat(o.price); else s = "需要" + o.integral + "爱心";
            if (parseInt(o.total_num) <= 0) return void a.setData({
                showModel: !0,
                content: "已领完,来晚一步",
                status: 1
            });
            if (parseInt(o.num) >= parseInt(o.user_num)) return o.type = 1, void a.setData({
                showModel: !0,
                content: "兑换次数已达上限",
                status: 1,
                coupon_list: n
            });
            getApp().core.showModal({
                title: "确认兑换",
                content: s,
                success: function (t) {
                    t.confirm && (0 < parseFloat(o.price) ? (getApp().core.showLoading({
                        title: "提交中"
                    }), getApp().request({
                        url: getApp().integral.exchange_coupon,
                        data: {
                            id: o.id,
                            type: 2
                        },
                        success: function (e) {
                            0 == e.code && getApp().core.requestPayment({
                                _res: e,
                                timeStamp: e.data.timeStamp,
                                nonceStr: e.data.nonceStr,
                                package: e.data.package,
                                signType: e.data.signType,
                                paySign: e.data.paySign,
                                success: function (e) {
                                    wx.requestSubscribeMessage({
                                        tmplIds: ['_XGsVLLisG8_LTbDnBk_4yIr2GbwvkNi8aSsKiUN_80'],
                                        success(res) {
                                            console.log('订阅消息', res)
                                        }
                                    })
                                },
                                complete: function (t) {
                                    "requestPayment:fail" != t.errMsg && "requestPayment:fail cancel" != t.errMsg ? "requestPayment:ok" == t.errMsg && (o.num = parseInt(o.num),
                                        o.num += 1, o.total_num = parseInt(o.total_num), o.total_num -= 1, i = parseInt(i),
                                        i -= parseInt(o.integral), a.setData({
                                            showModel: !0,
                                            status: 4,
                                            content: e.msg,
                                            coupon_list: n,
                                            integral: i
                                        })) : getApp().core.showModal({
                                            title: "提示",
                                            content: "订单尚未支付",
                                            showCancel: !1,
                                            confirmText: "确认"
                                        });
                                }
                            });
                        },
                        complete: function () {
                            getApp().core.hideLoading();
                        }
                    })) : (getApp().core.showLoading({
                        title: "提交中"
                    }), getApp().request({
                        url: getApp().api.integral.exchange_coupon,
                        data: {
                            id: o.id,
                            type: 1
                        },
                        success: function (t) {
                            0 == t.code && (o.num = parseInt(o.num), o.num += 1, o.total_num = parseInt(o.total_num),
                                o.total_num -= 1, i = parseInt(i), i -= parseInt(o.integral), a.setData({
                                    showModel: !0,
                                    status: 4,
                                    content: t.msg,
                                    coupon_list: n,
                                    integral: i
                                }));
                        },
                        complete: function () {
                            getApp().core.hideLoading();
                        }
                    })));
                }
            });
        }
    },
    hideModal: function () {
        this.setData({
            showModel: !1
        });
    },
    couponInfo: function (t) {
        var e = t.currentTarget.dataset;
        getApp().core.navigateTo({
            url: "/pages/integral-mall/coupon-info/index?coupon_id=" + e.id
        });
    },
    goodsAll: function () {
        var t = this.data.goods_list, e = [];
        for (var a in t) {
            var n = t[a].goods;
            for (var o in t[a].cat_checked = !1, n) e.push(n[o]);
        }
        this.setData({
            index_goods: e,
            cat_checked: !0,
            goods_list: t
        });
    },
    catGoods: function (t) {
        var e = t.currentTarget.dataset, a = this, n = a.data.catList,nn = a.data.catList1;
        integral_catId = e.catId, integral_index = e.index;
        var o = e.index;
        var cur = integral_index; 
        //每个tab选项宽度占1/5
        var singleNavWidth = this.data.windowWidth / 4;
        //tab选项居中    
        console.log(';;;;;',o)                        
        this.setData({
            navScrollLeft: (o - 0.5) * singleNavWidth,
            goods_list: [],
        })      
        console.log(a.data.currentTab,o)
        if (this.data.currentTab == o) {
            return false;
        } else {
            this.setData({
                currentTab: o
            })
        }
        console.log(a.data)
        if (-1 === o) {
            var i = !0;
            for (var s in n) n[s].cat_checked = !1;
            for (var s in nn) nn[s].cat_checked1 = !1;
        }
        if (0 <= o) for (var s in n) n[s].id == n[o].id ? i = !(n[s].cat_checked = !0) : n[s].cat_checked = !1;
        if (0 <= o) for (var s in nn) nn[s].id == nn[o].id ? i = !(nn[s].cat_checked1 = !0) : nn[s].cat_checked1 = !1;
        a.setData({
            cat_checked1: i,
            catList1: n,
            cat_checked: i,
            catList: n,
            goods_list: [],
            catId: integral_catId
        });
        if (integral_catId === '0') {
            a.setData({
                page_url: a.data.promotion.page_url,
                pro_url: a.data.promotion.pro_url
            })
            console.log('dadadada===', a.data)
        } else {
            for (var i = 0; i < n.length; i++) {
                if (integral_catId === n[i].id) {
                    console.log('integral_catId===', a.data)
                    a.setData({
                        page_url: n[i].page_url,
                        pro_url: n[i].pro_url
                    })
                }
            }
        };
        page = 1, a.getGoodsList(integral_catId), a.hot_goods(integral_catId);
    },
    catGoods1: function (t) {
        var e = t.currentTarget.dataset, a = this, n = a.data.catList1;
        integral_catId = e.catId, integral_index = e.index;
        var o = e.index;
        var cur = integral_index; 
        //每个tab选项宽度占1/5
        var singleNavWidth = this.data.windowWidth / 4;
        //tab选项居中    
        console.log(';;;;;',o)                        
        this.setData({
            navScrollLeft: (o - 0.5) * singleNavWidth,
            goods_list: [],
        })      
        console.log(a.data.currentTab,o)
        if (this.data.currentTab == o) {
            return false;
        } else {
            this.setData({
                currentTab: o
            })
        }
        if (-1 === o) {
            var i = !0;
            for (var s in n) n[s].cat_checked1 = !1;
        }
        if (0 <= o) for (var s in n) n[s].id == n[o].id ? i = !(n[s].cat_checked1 = !0) : n[s].cat_checked1 = !1;
        a.setData({
            cat_checked1: i,
            catList1: n,
        });
    
        page = 1, a.getGoodsList(integral_catId);
    },
    happyland: function (e) {
        console.log(e)
        var that = this
        var catId = e.currentTarget.dataset.catId
        var name = e.currentTarget.dataset.name
        wx.navigateTo({
            url: '/pages/integral-mall/happyland/happyland?catId=' + catId + '&name=' + name + '&is_distributor=' + that.data.is_distributor,
        })
    },
    getGoodsList: function (t) {
        var a = this;
        - 1 === integral_index && a.setData({
            cat_checked: !0
        }), getApp().core.showLoading({
            title: "加载中"
        }), getApp().request({
            url: getApp().api.integral.goods_list,
            data: {
                page: page,
                cat_id: t
            },
            success: function (t) {
                if (0 === t.code) {
                    var e = a.data.goods_list;
                    0 < t.data.list.length && (0 < e.length && (e = e.concat(t.data.list)), 0 === e.length && (e = t.data.list)), 0 === t.data.list.length && getApp().core.showToast({
                        title: "没有更多啦",
                        icon: "none"
                    }),a.setData({
                            goods_list: e,
                            banner_list: t.data.banner_list,
                            totalCount: t.data.pagination.totalCount
                        }); if (!a.data.cat_checked) {
                        a.setData({
                            subcat: t.data.subcat
                        })
                    };
                }
            },
            complete: function () {
                getApp().core.hideLoading();
            }
        });
    },
    goodsInfo: function (t) {
        var e = t.currentTarget.dataset.goodsId;
        var goods_num = t.currentTarget.dataset.goods_num;
        console.log('商品参数', e)
        if(goods_num == 0){
            getApp().core.showToast({
                title: "此商品已售罄",
                icon: "none"
              })
        }else{
        //     wx.navigateTo({
        //         url: `plugin-private://wx34345ae5855f892d/pages/productDetail/productDetail?productId=${37698180}`,
        //   });
            wx.navigateTo({
                url: "/pages/integral-mall/goods-info/index?goods_id=" + e + "&integral=" + this.data.integral
            });
        }

    },

    onHide: function (t) {
        getApp().page.onHide(this);
    },
    onUnload: function (t) {
        getApp().page.onUnload(this);
    },
    onPullDownRefresh: function (t) {
        getApp().page.onPullDownRefresh(this);
    },
    onShareAppMessage: function () {
        getApp().page.onShareAppMessage(this);
        var t = getApp().getUser(), e = "", a = getApp().core.getStorageSync(getApp().const.WX_BAR_TITLE);
        for (var n in a) if ("pages/integral-mall/index/index" === a[n].url) {
            e = a[n].title;
            break;
        }
        return {
            path: "/pages/integral-mall/index/index?user_id=" + t.id,
            title: e || "爱心商城",
            imageUrl:'https://assets.renrentuibao.com/web%2Fuploads%2Fimage%2Fstore_1%2F3b85d3e8c75552f001566b3ec3ea518a5f086b16.jpg'
        };
    },
    onReachBottom: function (t) {

        var a = this
        console.log(a.data.goods_list.length, Number(a.data.totalCount))
        if (a.data.goods_list.length === Number(a.data.totalCount)) {
            console.log('到底了+++++++', t)
            getApp().core.showToast({
                title: "没有更多啦",
                icon: "none"
            })
        } else {
            page += 1
            // getApp().page.onReachBottom(this);
            this.getGoodsList(integral_catId);
        }

    },
    shuoming: function () {
        getApp().core.navigateTo({
            url: "/pages/integral-mall/shuoming/index"
        });
    },
    detail: function () {
        getApp().core.navigateTo({
            url: "/pages/integral-mall/detail/index"
        });
    },
    exchange: function () {
        getApp().core.navigateTo({
            url: "/pages/integral-mall/exchange/index"
        });
    },
    surprise: function (e) {
        var a = this
        if(a.data.is_distributor == 0){
            getApp().core.showToast({
                title: "需要申请成为推客才可参与",
                icon: "none"
            })
            return;
        }
            getApp().core.navigateTo({
                url: a.data.surprise.page_url
            });

    },
    register: function () {
        var a = this
        getApp().core.navigateTo({
            url: a.data.page_url
        });
    },
    //置顶功能
    scrollTopFun: function (e) {
        // console.log(e.detail);
        if (e.detail.scrollTop > 300) {//触发gotop的显示条件 
            this.setData({
                'scrollTop.goTop_show': true
            });
            // console.log(this.data.scrollTop)
        } else {
            this.setData({
                'scrollTop.goTop_show': false
            });
        }
    },
    goTopFun: function (e) {
        getApp().core.showLoading({
            title: "置顶中请稍后"
        })
        var _top = this.data.scrollTop.scroll_top;//发现设置scroll-top值不能和上一次的值一样，否则无效，所以这里加了个判断 
        if (_top == 1) {
            _top = 0;
        } else {
            _top = 1;
        }
        this.setData({
            'scrollTop.scroll_top': _top
        });
        getApp().core.hideLoading();
        console.log("----");
        console.log(this.data.scrollTop)

    },
    remind: function (e) {
        wx.navigateTo({
            url: '/pages/free/free?remind=true' ,
        })
    },
    luck_draw:function(e){
        wx.setStorageSync('adds', '1')
        this.setData({
          remind: false,
        })
        wx.redirectTo({
          url: '/pages/luck-draw/luck-draw',
        })
      },
    guanb: function (e) {
        wx.setStorageSync('adds', '1')
        this.setData({
            remind: false
        })
    },
    exchange:function(e){
        this.setData({
          remind: false,
        })
        wx.setStorageSync('adds', '1')
        wx.redirectTo({
          url: '/pages/exchange/exchange',
        })
      },
      order:function(e){
        this.setData({
          remind: false,
        })
        wx.setStorageSync('adds', '1')
        wx.redirectTo({
          url: '/pages/order/order?status=1',
        })
      },
});